'use strict';
import {useCallback, useEffect, useState} from "react";

function UseClientWH() {
  const [clientWidth, setClientWidth] = useState<number>(0);
  const [clientHeight, setClientHeight] = useState<number>(0);

  const handleResize = useCallback(
    throttle(() => {
      setClientWidth(document.documentElement.clientWidth || document.body.clientWidth)
      setClientHeight(document.documentElement.clientHeight || document.body.clientHeight)
    }, 100),
    []
  )

  useEffect(() => {

    handleResize()

    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize);
    }
  }, []);

  return {
    clientWidth,
    clientHeight
  }
}


// 简单的节流函数实现
function throttle(fn: Function, delay: number) {
  let lastCall = 0;
  return function (...args: any[]) {
    const now = new Date().getTime();
    if (now - lastCall < delay) return;
    lastCall = now;
    return fn(...args);
  };
}

export default UseClientWH;